# Kestrel: An XMPP-based Many-Task Computing Scheduler
# Author: Lance Stout <lancestout@gmail.com>
#
# Copyright 2009-2010 Clemson University
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import yaml

from kestrel.core.datatypes import Worker, Job, Task
from kestrel.manager import WorkerPool, JobQueue


class Policy(object):
    def __init__(self, kernel):
        """
        The policy module provides the logic for choosing to handle
        or deny any requests independent of how those requests
        would actually be processed.

        Events listened for by this module:
          job/received
          profile/received

        Events raised by this module:
          job/approved
          job/rejected
          profile/approved
        """
        self.kernel = kernel
        self.events = {'job/received': self.approve_job,
                       'job/cancel': self.approve_cancellation,
                       'profile/received': self.approve_worker}
        self.kernel.register(self)


    def approve_job(self, job_msg):
        """Analyzes and approves or rejects tasks for execution."""
        job = Job(job_msg)

        # If the task contains errors:
        # self.kernel.event("job/malformed")

        # If task is not from an approved source,
        # or is against current policy:
        # self.kernel.event("job/rejected", job)

        # Otherwise:
        self.kernel.event("job/approved", job)


    def approve_cancellation(self, msg):
        """Check that a cancellation notice is valid."""
        # If the cancellation notice is from the job's source
        # and it is for the same job ID, then cancel.
        self.kernel.event('job/cancelled', msg)


    def approve_worker(self, msg):
        """
        Approves or rejects worker profiles to control
        which worker agents are able to receive tasks.
        """
        worker = Worker(msg)

        # If the worker does not meet some requirement
        # (such as included in a white list of JIDs)
        # then do nothing for now.

        # Otherwise:
        self.kernel.event('profile/approved', worker)
